package logic

import (
	"baidutieba/models/cache"
	"baidutieba/models/mysql"
	"baidutieba/pkg"
	"baidutieba/tiebarpc/internal/svc"
	"baidutieba/tiebarpc/tiebarpc"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *tiebarpc.RegisterRequest) (*tiebarpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+in.Account)
	if get.Val() != in.SendCode {
		return nil, fmt.Errorf("验证码获取失败")
	}
	var user mysql.User
	mysql.DB.Debug().Where("account", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("当前账号已存在,请前去登录")
	}
	if user.Account >= "1" {
		return nil, fmt.Errorf("同一个手机号只能在项目中注册一次")
	}
	m := mysql.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码不对")
	}
	mysql.DB.Create(&m)
	return &tiebarpc.RegisterResponse{
		Id: int64(m.ID),
	}, nil
}
